package com.xyhuo.leetcode.december;

import com.xyhuo.leetcode.common.ListNode;

/**
 * 两两交换链表中的节点
 * https://leetcode.cn/problems/swap-nodes-in-pairs/
 *
 * @time 2023/12/12
 */
public class SwapPairs {

//    public static void main(String[] args) {
//        ListNode l1 = new ListNode(1);
//        ListNode l2 = new ListNode(2);
//        ListNode l3 = new ListNode(3);
//        ListNode l4 = new ListNode(4);
//        l1.next = l2;
//        l2.next = l3;
//        l3.next = l4;
//
//        SwapPairs sp = new SwapPairs();
//        sp.swapPairs(l1);
//    }

    public ListNode swapPairs(ListNode head) {
        ListNode tmp = head;

        ListNode ans = head;
        ListNode last = null;
        while (tmp != null) {
            ListNode tmpNext = tmp.next;
            if (tmpNext != null) {
                ListNode next = tmpNext.next;
                tmp.next = next;
                tmpNext.next = tmp;
                if (last == null) {
                    ans = tmpNext;
                } else {
                    last.next = tmpNext;
                }
                last = tmp;
                tmp = next;
            } else {
                break;
            }
        }
        return ans;
    }
}
